package com.wannengbang.cloudleader.shop;


import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ethanhua.skeleton.Skeleton;
import com.ethanhua.skeleton.SkeletonScreen;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.base.BaseFragment;
import com.wannengbang.cloudleader.base.DataCallBack;
import com.wannengbang.cloudleader.bean.ShopBindBean;
import com.wannengbang.cloudleader.bean.ShopListBean;
import com.wannengbang.cloudleader.bean.UserInfoBean;
import com.wannengbang.cloudleader.event.BindMachinesEvent;
import com.wannengbang.cloudleader.homepage.BountyListActivity;
import com.wannengbang.cloudleader.mine.model.MineModelImpl;
import com.wannengbang.cloudleader.service.BankCardListActivity;
import com.wannengbang.cloudleader.shop.adapter.ShopListAdapter;
import com.wannengbang.cloudleader.shop.model.IShopModel;
import com.wannengbang.cloudleader.shop.model.ShopModelImpl;
import com.wannengbang.cloudleader.utils.Dp2Px;
import com.wannengbang.cloudleader.widget.AppTitleBar;
import com.wannengbang.cloudleader.widget.CommonNoTitleDialog;
import com.wannengbang.cloudleader.widget.MaterialHeader;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 *
 */
public class ShopFragment extends BaseFragment implements OnRefreshLoadMoreListener {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.layout_title)
    LinearLayout layoutTitle;
    @BindView(R.id.nestedScrollView)
    NestedScrollView nestedScrollView;
    @BindView(R.id.tv_total_num)
    TextView tvTotalNum;
    @BindView(R.id.ll_binding_machines)
    LinearLayout llBindingMachines;
    @BindView(R.id.ll_exchange_list)
    LinearLayout llExchangeList;
    @BindView(R.id.ll_integral_list)
    LinearLayout llIntegralList;
    private Unbinder unbinder;
    private IShopModel shopModel;
    private ShopListAdapter listAdapter;
    private List<ShopListBean.DataBean.ItemListBean> beanList;
    private SkeletonScreen skeletonScreen;
    private int page = 1;
    private ImmersionBar immersionBar;
    private boolean isSetBar;
    private CommonNoTitleDialog.Builder dialogBuild;
    private ShopBindBean bindBean;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_shop, container, false);
        unbinder = ButterKnife.bind(this, view);
        registerEventBus();
        initView();
        requestUserInfo();
        requestGoodsIndex();
        return view;
    }

    @Override
    public void initImmersionBar() {
        immersionBar = ImmersionBar.with(this)
                .statusBarDarkFont(false)
                .navigationBarDarkIcon(true)
                .navigationBarColor(R.color.white)
                .statusBarDarkFont(false, 0.2f);
        immersionBar.init();
    }

    public void initView() {
        refreshLayout.setRefreshHeader(new MaterialHeader(mActivity));//设置Header
        refreshLayout.setRefreshFooter(new ClassicsFooter(mActivity));//设置Footer
        refreshLayout.setOnRefreshLoadMoreListener(this);
        shopModel = new ShopModelImpl();
        beanList = new ArrayList<>();
        listAdapter = new ShopListAdapter(beanList);
        recyclerView.setLayoutManager(new GridLayoutManager(mActivity, 2));
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int i = parent.getChildLayoutPosition(view) % 2;//每行2个
                switch (i) {
                    case 0://第一个
                        outRect.left = (int) Dp2Px.dp2Px(15);
                        outRect.right = (int) Dp2Px.dp2Px(5);
                        break;
                    case 1://第二个
                        outRect.left = (int) Dp2Px.dp2Px(5);
                        outRect.right = (int) Dp2Px.dp2Px(15);
                        break;
                }
            }
        });
        recyclerView.setAdapter(listAdapter);
        listAdapter.setOnCallBackListener((type, position) -> {
            if (type == 1) {
                Intent intent = new Intent(mActivity, ShopGoodsDetailsActivity.class);
                intent.putExtra("goods_id", beanList.get(position).getId() + "");
                startActivity(intent);
            }
        });
        skeletonScreen = Skeleton.bind(recyclerView)
                .adapter(listAdapter)
                .color(R.color.shimmer_color_2)
                .shimmer(true)
                .angle(20)
                .frozen(false)
                .duration(1000)
                .count(20)
                .load(R.layout.item_skeleton_shop_list)
                .show();

        int height = (int) Dp2Px.dp2Px(100);
        nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY <= 0) {   //设置标题的背景颜色
                    layoutTitle.setBackgroundColor(Color.argb((int) 0, 255, 255, 255));
                    viewLine.setBackgroundColor(Color.argb((int) 0, 243, 243, 243));
                    titleBar.setTitleColor(getResources().getColor(R.color.white));
                    immersionBar.statusBarDarkFont(false).statusBarDarkFont(false, 0.2f).init();
                    isSetBar = false;
                } else if (scrollY > 0 && scrollY <= height) { //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
                    float scale = (float) scrollY / height;
                    float alpha = (255 * scale);
                    layoutTitle.setBackgroundColor(Color.argb((int) alpha, 255, 255, 255));
                    viewLine.setBackgroundColor(Color.argb((int) alpha, 243, 243, 243));
                } else {    //滑动到banner下面设置普通颜色
                    if (!isSetBar) {
                        layoutTitle.setBackgroundColor(Color.argb((int) 255, 255, 255, 255));
                        viewLine.setBackgroundColor(Color.argb((int) 255, 243, 243, 243));
                        titleBar.setTitleColor(getResources().getColor(R.color.text_color_2));
                        immersionBar.statusBarDarkFont(true).statusBarDarkFont(true, 0.2f).init();
                        isSetBar = true;
                    }
                }
            }
        });
        requestBindIndex();
    }

    @Subscribe
    public void bindMachinesEvent(BindMachinesEvent event) {
        shopModel.requestIntegralBindIndex(new DataCallBack<ShopBindBean>() {
            @Override
            public void onSuccessful(ShopBindBean bean) {
                bindBean = bean;
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestBindIndex() {
        shopModel.requestIntegralBindIndex(new DataCallBack<ShopBindBean>() {
            @Override
            public void onSuccessful(ShopBindBean bean) {
                bindBean = bean;
                if (bean.getData() == null || bean.getData().size() == 0) {
                    dialogBuild = new CommonNoTitleDialog.Builder(mActivity);
                    dialogBuild.setMessage("请先绑定机具，绑定后刷卡奖励金币");
                    dialogBuild.setPositiveVersionButton("去绑定", v -> {
                        dialogBuild.dismiss();
                        dialogBuild = null;
                        skipToActivity(BindingMachinesActivity.class);
                    });
                    dialogBuild.setNegativeButton("取消", v -> {
                        dialogBuild.dismiss();
                        dialogBuild = null;
                    });
                    dialogBuild.setCancelable(false);
                    dialogBuild.show();
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    private boolean isViewCreated; // 界面是否已创建完成
    private boolean isVisibleToUser; // 是否对用户可见

    /**
     * Fragment 创建期间setUserVisibleHint()方法是在onActivityCreated()之前被调用
     */
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        this.isVisibleToUser = isVisibleToUser;
        tryLoadData();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewCreated = true;
        tryLoadData();
    }

    public void tryLoadData() {
        if (isViewCreated && isVisibleToUser) {
            requestUserInfo();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        requestUserInfo();
    }

    /**
     * 用户信息
     */
    public void requestUserInfo() {
        new MineModelImpl().requestMine(new DataCallBack<UserInfoBean>() {
            @Override
            public void onSuccessful(UserInfoBean bean) {

                String s = new Gson().toJson(bean);

                Log.e("金币余额",s);
                tvTotalNum.setText(bean.getData().getIntegral_balance());
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    private void requestGoodsIndex() {
        shopModel.requestIntegralGoods(page, new DataCallBack<ShopListBean>() {
            @Override
            public void onSuccessful(ShopListBean bean) {
                if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                    beanList.addAll(bean.getData().getItemList());
                    if (page == 1) {
                        refreshLayout.finishRefresh();
                    } else {
                        refreshLayout.finishLoadMore();
                    }
                } else {
                    if (page != 1) {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.finishRefresh();
                    }
                }
                if (beanList.size() > 0) {
                    llNoData.setVisibility(View.GONE);
                } else {
                    llNoData.setVisibility(View.VISIBLE);
                }
                listAdapter.notifyDataSetChanged();
                if (page == 1) {
                    skeletonScreen.hide();
                }
            }

            @Override
            public void onFailed(String msg, String code) {
                skeletonScreen.hide();
            }
        });
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        requestGoodsIndex();
        refreshLayout.finishLoadMore(30000);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshData();
    }

    public void refreshData() {
        page = 1;
        beanList.clear();
        requestGoodsIndex();
        refreshLayout.finishRefresh(30000);
    }

    @OnClick({R.id.ll_binding_machines, R.id.ll_exchange_list, R.id.ll_integral_list, R.id.ll_consume_plan, R.id.ll_merchant_bounty})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_binding_machines:
                skipToActivity(BindingMachinesActivity.class);
                break;
            case R.id.ll_exchange_list:
                skipToActivity(ShopMyOrderListActivity.class);
                break;
            case R.id.ll_integral_list:
                skipToActivity(IntegralListActivity.class);
                break;
            case R.id.ll_consume_plan:
                if (bindBean == null) {
                    return;
                }
                if (bindBean.getData() == null || bindBean.getData().size() == 0) {
                    dialogBuild = new CommonNoTitleDialog.Builder(mActivity);
                    dialogBuild.setMessage("请先绑定机具");
                    dialogBuild.setPositiveVersionButton("去绑定", v -> {
                        dialogBuild.dismiss();
                        dialogBuild = null;
                        skipToActivity(BindingMachinesActivity.class);
                    });
                    dialogBuild.setNegativeButton("取消", v -> {
                        dialogBuild.dismiss();
                        dialogBuild = null;
                    });
                    dialogBuild.setCancelable(false);
                    dialogBuild.show();
                    return;
                }
                skipToActivity(BankCardListActivity.class);
                break;
            case R.id.ll_merchant_bounty:
                skipToActivity(BountyListActivity.class);
                break;
        }
    }
}
